﻿var HUB = function () {
	var self = {};

	var EVENT_PREFIX = "hubbub-hub-";

	self.CLOSE = EVENT_PREFIX + "close";
	self.DELETE_BUBS = EVENT_PREFIX + "delete-bubs";

	var onClose = function (evt) {
		var mdl, inst, node;

		if(typeof evt === "object") {
			mdl = document.getElementById("mdl-gadgets");
			if(mdl) {
				inst = mdl.getInstanceDocument("inst-close");
				if(inst) {
					node = inst.selectSingleNode("close");
					if(node) {
						node.text = evt.strParam;
						mdl.rebuild();
						mdl.dispatchEvent(evt);
					}
				}
			}
		}
	};

	var onDeleteBubs = function (evt) {
		var mdl, inst, node;

		if(typeof evt === "object") {
			mdl = document.getElementById("mdl-gadgets");
			if(mdl) {
				inst = mdl.getInstanceDocument("inst-delete-bubs");
				if(inst) {
					node = inst.selectSingleNode("delete-bubs");
					if(node) {
						node.text = evt.strParam;
						mdl.rebuild();
						mdl.dispatchEvent(evt);
					}
				}
			}
		}
	};

	var handleEventHub = function (evt) {
		try {
			switch(evt.type) {
				case self.CLOSE:
					onClose(evt);
					break;
				case self.DELETE_BUBS:
					onDeleteBubs(evt);
					break;
			}
		} catch(e) {
		}
	};

	// Initialise the default handler for hubbub-hub-close.
	self.initHandlers = function () {
		var rc = EVENTS.listen(this.CLOSE, handleEventHub);

		if(rc === EVENTS.RETURN_SUCCESS) {
			rc = EVENTS.listen(this.DELETE_BUBS, handleEventHub);
		}

		return rc;
	};

	return self;
} ();

// Global-abated "member" functions can not be called from XPath,
// so we provide these quasi-namespaced alternatives as well.
function HUB_initHandlers() {
	return HUB.initHandlers();
}
